//
//  BCHeadSendLetterTableViewController.m
//  aiteshangcheng
//
//  Created by mac on 2017/6/9.
//  Copyright © 2017年 aite. All rights reserved.
//

#import "BCHeadSendLetterTableViewController.h"
#import "Utility.h"
//#import "Config.h"
#import "AFHTTPRequestOperationManager.h"
#import "iToast.h"
#define COLOR(R, G, B, A)   [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:A]
#define kScreanWidth   [UIScreen mainScreen].bounds.size.width
//判断字符串是否为空
#define isStringEmpty(a) ([a isEqual:[NSNull null]] || a == nil || [a isEqualToString:@""])

@interface BCHeadSendLetterTableViewController ()<UITextViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource>
@property (nonatomic, strong) UITextField *nameTextField;

@property (nonatomic, strong) UITextField *titleTextField;

@property (nonatomic, strong) UITextView *contentTextView;

@property (nonatomic, strong) UIView *dataPickerView;

@property (nonatomic, strong) UIPickerView *pickerView;

@property (nonatomic, strong) NSArray *workerArray;

@property (nonatomic, assign) NSInteger selectRow;

@end

@implementation BCHeadSendLetterTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNAV];
    self.selectRow = 0;
    
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.scrollEnabled = YES;
    
    self.dataPickerView = [[UIView alloc]initWithFrame:self.view.frame];
    self.dataPickerView.backgroundColor =
    COLOR(1, 1, 1, 0.5);
    self.dataPickerView.hidden = YES;
    [self.view addSubview:self.dataPickerView];
    
    UIView *whiteView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 300, kScreanWidth, 300)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.dataPickerView addSubview:whiteView];
    
    //取消按钮
    UIButton *cancelButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 50)];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(cancelButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [whiteView addSubview:cancelButton];
    
    //确定按钮
    UIButton *confirmButton = [[UIButton alloc]initWithFrame:CGRectMake(kScreanWidth - 100, 0, 100, 50)];
    [confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    [confirmButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [confirmButton addTarget:self action:@selector(confirmButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [whiteView addSubview:confirmButton];
    
    self.pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 50, kScreanWidth, 250)];
    self.pickerView.dataSource = self;
    self.pickerView.delegate = self;
    [self.pickerView selectRow:0 inComponent:0 animated:NO];
    [whiteView addSubview:self.pickerView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setNAV{
    //ICON_64_
//    [self.navigationController.navigationBar setBackgroundImage:[self createImageWithColor:[UIColor orangeColor]] forBarMetrics:UIBarMetricsDefault];
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    [title setBackgroundColor:[UIColor clearColor]];
    [title setTextAlignment:NSTextAlignmentCenter];
    title.textColor = [UIColor whiteColor];
    title.font = [UIFont systemFontOfSize:20];
    title.text = @"发送站内信";
    [title sizeToFit];
    self.navigationItem.titleView = title;
    
    CGRect rect = title.frame;
    title.frame = CGRectMake((kScreanWidth - rect.size.width)/2, (44 - rect.size.height)/2, rect.size.width, rect.size.height);
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"fanhui"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ] style:UIBarButtonItemStyleDone target:self action:@selector(backHomeViewController)];
    self.navigationItem.leftBarButtonItem = backItem;
}
//根据颜色生成图片
- (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
#pragma mark - 返回上一级界面
- (void)backHomeViewController{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return 4;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
    cell.selectionStyle  = UITableViewCellSelectionStyleNone;
    if (indexPath.row == 0) {
//        cell.textLabel.text = @"发送对象";
        UILabel *textLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, 100, 44)];
        textLabel.text = @"发送对象";
        [cell addSubview:textLabel];
//        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        self.nameTextField = [[UITextField alloc]initWithFrame:CGRectMake(kScreanWidth - 200, 0, 170, 44)];
        self.nameTextField.placeholder = @"多个用英文字符','隔开";
        
        [cell addSubview:self.nameTextField];
        
        UIView *lineView = [[UILabel alloc]initWithFrame:CGRectMake(0, 43, kScreanWidth, 1)];
        lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [cell addSubview:lineView];
        
        cell.backgroundColor = [UIColor whiteColor];
    }
    
    if (indexPath.row == 1) {
        self.titleTextField = [[UITextField alloc]initWithFrame:CGRectMake(20, 0, kScreanWidth - 40, 44)];
        self.titleTextField.placeholder = @"标题";
        [cell addSubview:self.titleTextField];
        
        UIView *lineView = [[UILabel alloc]initWithFrame:CGRectMake(0, 43, kScreanWidth, 1)];
        lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [cell addSubview:lineView];
        cell.backgroundColor = [UIColor whiteColor];
    }
    if (indexPath.row == 2) {
        self.contentTextView = [[UITextView alloc]initWithFrame:CGRectMake(20, 10, kScreanWidth - 40, 200)];
        self.contentTextView.text = @"内容";
        self.contentTextView.delegate = self;
        [cell addSubview:self.contentTextView];
        cell.backgroundColor = [UIColor whiteColor];
    }
    if (indexPath.row == 3) {
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(20, 20, kScreanWidth - 40, 40)];
        button.backgroundColor = COLOR(235, 104, 23, 1);
        [button setTitle:@"发送" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(sendLetter:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:button];
        
    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 2) {
        return 220;
    }else if (indexPath.row == 3){
        return 80;
    }else{
        return 44;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
//        NSDictionary *getDic = @{@"key" : [UserManager shareUser].key,
//                                 @"page" : @"100",
//                                 @"curpage" : @"1"};
//        
//        [BCHttpManager httpGetRequestByJSON:getDic Url:bcurl servicesCode:@"index.php?act=decorate_preside&op=list" Success:^(id json) {
//            if ([json[@"code"] integerValue] == 200) {
//                if ([json[@"datas"][@"list"] isKindOfClass:[NSArray class]]) {
//                    NSArray *listArray = json[@"datas"][@"list"];
//                    if (listArray.count > 0) {
//                        self.workerArray = listArray;
//                        self.dataPickerView.hidden = NO;
//                        [self.pickerView reloadAllComponents];
//                    }
//                }
//            }
//        } Failure:^(NSError *error) {
//            alert(nil, AFTfailStr);
//        }];
        
    }
}

#pragma mark - UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@"内容"]) {
        textView.text = @"";
    }
}
- (void)textViewDidEndEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
        textView.text = @"内容";
    }
}

#pragma mark - 点击事件
- (void)sendLetter:(UIButton *)button{
    
    if (isStringEmpty(self.nameTextField.text)) {
        [iToast makeToast:@"请输入发送对象"];
    }else if (isStringEmpty(self.contentTextView.text)){
        [iToast makeToast:@"请输入内容"];
    }else{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择消息类型" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *firstAction = [UIAlertAction actionWithTitle:@"留言" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self sendLetterWithStyle:@"2"];
        }];
        UIAlertAction *secondAction = [UIAlertAction actionWithTitle:@"私信" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self sendLetterWithStyle:@"0"];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:firstAction];
        [alertController addAction:secondAction];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
}

- (void)sendLetterWithStyle:(NSString *)typeString{
    NSDictionary *postDic = @{
//                              @"key" : [UserManager shareUser].key,
                              @"msg_content" : self.contentTextView.text,
                              @"to_member_name" : self.nameTextField.text,
                              @"msg_type" : typeString};

    
    //    [BCHttpManager httpPostRequestByJSON:postDic Url:bcurl servicesCode:@"index.php?act=member_message&op=savemsg" Success:^(id json) {
//        if ([json[@"datas"] isKindOfClass:[NSString class]]) {
//            [[iToast makeToast:json[@"datas"]]show];
//            [self.navigationController popViewControllerAnimated:YES];
//        }else{
//            [[iToast makeToast:json[@"datas"][@"error"]]show];
//        }
//    } Failure:^(NSError *error) {
//        
//    }];
//    [self httpRequest:sendMall and:postDic and:0];
}

- (void)httpRequest:(NSString *)urlStr and:(NSDictionary *)dict and:(NSInteger)num
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    __weak typeof(self) weakSelf = self;
    [manager POST:urlStr parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSData *resData = [[NSData alloc] initWithData:[operation.responseString dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"123 %@", resultDic);
        NSInteger code = [[resultDic objectForKey:@"code"] integerValue];
        id datas = [resultDic objectForKey:@"datas"];
        
        if (num == 0) {
            if (code == 200) {
                if ([resultDic[@"datas"] isKindOfClass:[NSString class]]) {
                    [[iToast makeToast:resultDic[@"datas"]]show];
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }else{
                    [[iToast makeToast:resultDic[@"datas"][@"error"]]show];
                }
                
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        alert(nil, AFTfailStr);
    }];
}


- (void)cancelButtonClicked:(UIButton *)button{
    self.dataPickerView.hidden = YES;
    
}

- (void)confirmButtonClicked:(UIButton *)button{
    self.dataPickerView.hidden = YES;
//    NSDictionary *workerDic = self.workerArray[self.selectRow];
//    self.nameLabel.text = workerDic[@"member_truename"];
}

#pragma mark - pickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return self.workerArray.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSDictionary *workerDic = self.workerArray[row];
    return workerDic[@"member_truename"];
}
#pragma mark - pickerViewDelegate
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    self.selectRow = row;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
